﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Windows.Forms;

namespace XtyDesktop
{
    public class common
    {
        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        static extern int SystemParametersInfo(
            int uAction,
            int uParam,
            string lpvParam,
            int fuWinIni
            );

        #region 定义，写注册表，自启动
        private const string REGKEYAutoRun = @"SoftWare\MicroSoft\Windows\CurrentVersion\Run";//开机运行的注册表路径
        private const string REGKEYIsFirstRun = @"SoftWare\XtyDesktop";
        private const string REGKEYDesktopPath = @"Control Panel\Desktop";
        private const string IsFirstRunKeyName = "IsFirstRun";
        #endregion

        #region 并写注册表自启动
        public static bool IsFirstRun = true;
        
        public static void Init()
        {
            int key = Convert.ToInt32(GetRegistValue(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName));
            if (key == 2)
            {
                SetRegist(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName, "1");
                key = 1;
            }

            IsFirstRun = Convert.ToBoolean(key);

            if (IsFirstRun) //第一次启动
            {
                SetRegist(Registry.LocalMachine, REGKEYAutoRun, Application.ProductName, "\"" + common.GetMapPath("XtyDesktop.exe") + "\"");//写到注册表中，开机自启动
                SetRegist(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName, "0");
            }
        }
        /// <summary>
        /// 卸载
        /// </summary>
        public static void Uninst()
        {
            DeleteRegist(Registry.LocalMachine, REGKEYAutoRun, Application.ProductName);
            DeleteRegist(Registry.LocalMachine, REGKEYIsFirstRun, IsFirstRunKeyName);

            string defaultImg = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Microsoft\\Windows\\Wallpaper1.jpg";
            //win 7以上
            if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 0)
            {
                defaultImg = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+"\\Microsoft\\Windows\\Themes\\TranscodedWallpaper.jpg";
            }

            SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "Wallpaper", defaultImg);
            SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "ConvertedWallpaper", defaultImg);
            SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "OriginalWallpaper", defaultImg);

            SystemParametersInfo(20, 0, defaultImg, 0x2);
        }
        /// <summary>
        /// 删除注册表值节点
        /// </summary>
        /// <param name="regKey"></param>
        /// <param name="REGKEY"></param>
        /// <param name="name"></param>
        /// <param name="Path"></param>
        static void DeleteRegist(RegistryKey regKey, string REGKEY, string name)
        {
            try
            {
                RegistryKey reg = regKey.OpenSubKey(REGKEY, true);
                if (reg != null)
                {
                    reg.DeleteValue(name);
                    reg.Close();
                }
            }
            catch { }
        }
        /// <summary>
        /// 写注册表值
        /// </summary>
        /// <param name="regKey"></param>
        /// <param name="REGKEY"></param>
        /// <param name="name"></param>
        /// <param name="Path"></param>
        static void SetRegist(RegistryKey regKey, string REGKEY, string name, string Path)
        {
            try
            {
                RegistryKey reg = regKey.OpenSubKey(REGKEY, true);

                if (reg == null)
                {
                    reg = regKey.CreateSubKey(REGKEY);
                }
                reg.SetValue(name, Path);
                reg.Close();
            }
            catch { }
        }
        /// <summary>
        /// 获取注册表值
        /// </summary>
        /// <param name="regKey"></param>
        /// <param name="REGKEY"></param>
        /// <param name="name"></param>
        /// <param name="Path"></param>
        static string GetRegistValue(RegistryKey regKey, string REGKEY, string name)
        {
            RegistryKey reg = regKey.OpenSubKey(REGKEY, true);

            if (reg != null)
            {
                string value = reg.GetValue(name, "2").ToString();
                reg.Close();
                return value;
            }
            else
                return "2";
        }
        #endregion

        static string HTMLSubstring(string html, string startLab, string endLab)
        {
            string result = string.Empty;
            try
            {
                int start = html.IndexOf(startLab);
                int end = html.IndexOf(endLab, start);
                if (end > start)
                {
                    start = start + startLab.Length;
                    int len = end - start;
                    result = html.Substring(start, len);
                }
            }
            catch { }

            return result;
        }

        static string GetPage(string sourceURL, string charset)
        {
            string html = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceURL);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705)";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(charset)))
                    {
                        html = reader.ReadToEnd();
                    }
                }
            }
            catch { }

            return html;
        }

        static Image GetWebImage(string imageURL)
        {
            Image myImage = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imageURL);
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = "GET";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705)";
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    myImage = Image.FromStream(response.GetResponseStream());
                }
            }
            catch { }

            return myImage;
        }

        public static string GetMapPath(string fileName)
        {
            return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
        }

        /// <summary>
        /// 桌面壁纸抓取，抓取 必应http://cn.bing.com 首页的壁纸图片地址，最后保存图片。
        /// </summary>
        public static void UpdateImage()
        {
            string deskImgPath = GetMapPath("desktop.bmp");
            string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".jpg"; // 图片名称
            string filePath = GetMapPath("images");
            string imgFullPath = filePath + "\\" + fileName;

            if (!File.Exists(imgFullPath))  //今日图片不存在，则下载
            {
                string sourceURL = "http://cn.bing.com";
                string charset = "utf-8";
                string pageContent = GetPage(sourceURL, charset);
                string imgUrl = HTMLSubstring(GetPage(sourceURL, charset), "g_img={url:'", "',");
                if (imgUrl == string.Empty || !Regex.Match(imgUrl, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?").Success)
                {
                    Console.WriteLine("无法获取图片");
                    return;
                }

                Image bmp = GetWebImage(imgUrl);
                if (bmp == null)
                {
                    Console.WriteLine("木有找到图片.");
                    return;
                }

                try
                {
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    bmp.Save(imgFullPath, ImageFormat.Jpeg);//保存下载的图片
                    bmp.Save(deskImgPath, ImageFormat.Bmp);
                }
                finally
                {
                    bmp.Dispose();
                }

                if (File.Exists(deskImgPath))
                {
                    if (IsFirstRun) //第一次启动
                    {
                        SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "Wallpaper", deskImgPath);
                        SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "ConvertedWallpaper", deskImgPath);
                        SetRegist(Registry.CurrentUser, REGKEYDesktopPath, "OriginalWallpaper", deskImgPath);
                    }
                    SystemParametersInfo(20, 0, deskImgPath, 0x2);
                    Console.WriteLine("设置成功!");
                }
                else
                {
                    Console.WriteLine("木有找到图片。");
                }
            }
        }
    }
}
